package tableprocessor;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.hibernate.FlushMode;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 *
 * @author Gleb
 */
public class DBProduceDAO
{
    private final static Logger logger = LoggerFactory.getLogger(DBProduceDAO.class);
    public static Iterator<DBProduce> getProduceByCathegory(int cid)
    {
        Transaction tx = null;
        List <DBProduce> rlist = null;
        Session session = SessionFactoryUtil.getInstance().getCurrentSession();
        try
        {
            session.setFlushMode(FlushMode.NEVER);
            tx = session.beginTransaction();
            Query q = session.createQuery("SELECT rlist FROM DBProduce AS rlist WHERE cathegory_id =:cid");//"SELECT rlist FROM DBProduce AS rlist ");
            q.setParameter("cid", cid);
            rlist = q.list();
            tx.commit();
            return rlist.iterator();
        }
        catch (RuntimeException e)
        {
            e.printStackTrace();
            if (tx != null && tx.isActive())
            {
                try {tx.rollback();}
                catch (HibernateException e1){e1.printStackTrace();}
            }
        }
        return null;
    }
    public static Iterator<Integer> getCathegoryList()
    {
        Transaction tx = null;
        List <DBProduce> rlist = null;
        Session session = SessionFactoryUtil.getInstance().getCurrentSession();
        try
        {
            session.setFlushMode(FlushMode.NEVER);
            tx = session.beginTransaction();
            rlist = (List<DBProduce>)session.createQuery("FROM DBProduce").list();//"SELECT rlist FROM DBProduce AS rlist ");
            //rlist = q.list();
            tx.commit();
            Set<Integer> set = new LinkedHashSet<Integer>();
            for (int i = 0; i < rlist.size(); i++)
            {
                set.add(rlist.get(i).getCathegory_id());
            }
            return set.iterator();
        }
        catch (RuntimeException e)
        {
            e.printStackTrace();
            if (tx != null && tx.isActive())
            {
                try {tx.rollback();}
                catch (HibernateException e1){e1.printStackTrace();}
            }
        }
        return null;
    }
}
